# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import json
import re
import time
from setting import PROXY, logger
import requests
import random

"""
 Author:Lu
 E-mail:luliangce@gmail.com
 Created:2018/3/31
 Update:

 定义模拟浏览器行为的抽象模型
 """
# TODO 接入连接池
if PROXY:
    p = random.choice(PROXY)
    logger.info("正在使用代理:{}".format(p))
    proxy = {
        "https": p,
        "http": p,
    }
else:
    proxy = {}
    logger.info("当前没有使用代理,需要可以访问外网的网络环境")


class Base(object):

    indexUrl = "https://www.instagram.com/"
    header = {
        "User-Agent": ("Mozilla/5.0 (Windows NT 10.0; Win64; x64)"
                       " AppleWebKit/537.36 (KHTML, like Gecko) "
                       "Chrome/61.0.3163.100 Safari/537.36"),
        "accept-encoding": "gzip, deflate, br",
        "accept-language": "zh-CN, zh;q = 0.8"
    }

    def __init__(self):
        self.proxy = proxy  # 初始化session的代理# TODO 代理目前写死
        self.s = requests.Session()  # 初始化一个session或者读取一个session
        self.s.headers.update(self.header)
        resp = self.s.get(self.indexUrl, proxies=proxy, timeout=10)
        self.cMid = resp.cookies.get("mid")
        self.cCsrf = resp.cookies.get("csrftoken")

    def post(self, url, data={}, is_ajax=True, header={}, file=None):
        """包装网络出口,统一挂代理,设置cookie关键参数,模拟浏览器行为


        Returns:
            [Response] -- requests模块的Response对象
        """

        # mid参数是一个加密字符串,目前不清楚作用,暂时保存
        self.cMid = self.s.cookies.get("mid")
        # csrftoken参数是web开发中防止恶意流量的一种方式,携带这个参数的post请求才会被服务器认可.
        # 一般通过COOKIE保存,每次都取出来,在ajax请求时携带x-csrf-token的cookie
        self.cCsrf = self.s.cookies.get("csrftoken")
        h = {"x-csrftoken": self.cCsrf,
             "X-Instagram-AJAX": "1",
             "origin": "https://www.instagram.com",
             "referer": "https://www.instagram.com/",
             "X-Requested-With": "XMLHttpRequest"}
        h.update(self.s.headers)  # post请求header和浏览器默认header合并
        if header:  # 如果存在自定义header,更新到h中
            h.update(h)
        p = dict(
            proxies=self.proxy,
            headers=h,
            verify=False,
            timeout=10)
        if data:
            p["data"] = data
        if file:
            p["files"] = file

        resp = self.s.post(url, **p)
        # 请求之后ins会自动刷新session中的csrftoken字段.
        return resp

    def get(self, url, is_ajax=False, data={}, header={}):
        """ 封装get方法 """
        h = {
            "origin": "https://www.instagram.com",
            "referer": "https://www.instagram.com/",
        }
        if is_ajax:
            h["x-requested-with"] = "XMLHttpRequest"
        h.update(self.s.headers)
        h.update(header)
        resp = self.s.get(url, headers=h, params=data,
                          timeout=10, proxies=self.proxy)
        return resp

    def login(self, username, password, email=None):
        url = "https://www.instagram.com/accounts/login/ajax/"
        param = dict(
            username=username,
            password=password,
            next="/"
        )
        resp = self.post(url, data=param)
        try:
            response = resp.json()
        except Exception as e:
            return False
        # 返回成功样例
        # {"authenticated": true, "user": true, "status": "ok"}
        if response.get("authenticated"):
            user_id = self.s.cookies.get("ds_user_id")
            self.user_id = user_id
            return True
        else:
            logger.info("登录失败")
            return False

    @property
    def logined(self):
        """ 当前登录状态,如果有用户id则表示已登录,否则为未登录.
            注册成功和登录成功会自动为类添加user_id属性

        """
        try:

            return bool(self.user_id)
        except:
            return False

    def refreshLoginStatus(self):
        """ 连接ins检查当前账户是否是登录状态
        """
        url = "https://www.instagram.com/web/activity/mark_checked/"

        data = dict(
            timestamp=str(time.time())
        )
        resp = self.post(url, data=data)
        try:
            if resp.json().get("status") == "ok":
                return True
        except:
            self.user_id = None
            return False

    def get_profile(self):
        url = "https://www.instagram.com/accounts/edit/"

        try:
            resp = self.get(url).text
            pattern = re.compile(r'"form_data":(.+?\})\}\]\}')
            g = json.loads(pattern.search(resp).groups()[0])
            self.profile = g
            return True
        except AttributeError:
            logger.info("没有找到资料")
        return False
